package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupkickwhitelist.WxqKickWhitelistDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupkickwhitelist.WxqKickWhitelistIdDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupkickwhitelist.WxqKickWhitelistQuery;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.es.EsWxGroupMember;
import com.uzai.console.entity.es.WxqKickWhitelist;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.wechatprivate.WxqKickWhitelistService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroup.WxGroupInfoVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupkickwhitelist.WxqKickWhitelistVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqKickWhitelistServiceImpl implements WxqKickWhitelistService {

    Logger logger = LoggerFactory.getLogger(WxqKickWhitelistServiceImpl.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;

    /**
     * 查询社群踢人白名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqKickWhitelistQuery
     * @return null
     */
    public Page<WxqKickWhitelistVo> findByPage(WxqKickWhitelistQuery wxqKickWhitelistQuery){
        //新建返回到页面的LIST对象
        List<WxqKickWhitelistVo> wxqKickWhitelistVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqKickWhitelistVo> page = new Page<>();
        wxqKickWhitelistQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxqKickWhitelistQuery.getMerId())));

        //白名单类型(0-群内踢人白名单 1-所有群踢人白名单)
        if(wxqKickWhitelistQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wxqKickWhitelistQuery.getType()));
        }

        //群微信id
        if(StringUtils.isNotBlank(wxqKickWhitelistQuery.getGroupWxid())){
            boolQuery.must(QueryBuilders.termQuery("groupWxid", wxqKickWhitelistQuery.getGroupWxid()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxqKickWhitelistQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid", wxqKickWhitelistQuery.getWxid()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        //查询群存不存在
        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WXQ_KICK_WHITElIST, searchSourceBuilder, wxqKickWhitelistQuery.getSize(), wxqKickWhitelistQuery.getFromIndex(), null, null, highlightField, wxqKickWhitelistQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxqKickWhitelist wxqKickWhitelist  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxqKickWhitelist.class);
                if(wxqKickWhitelist != null){
                    WxqKickWhitelistVo wxqKickWhitelistVo = new WxqKickWhitelistVo();
                    BeanUtils.copyProperties(wxqKickWhitelist, wxqKickWhitelistVo);

                    if(wxqKickWhitelistVo.getDeviceUniqueId() != null){
                        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxqKickWhitelistVo.getDeviceUniqueId(), wxqKickWhitelist.getMerId());
                        if(deviceWechatInfo != null){
                            wxqKickWhitelistVo.setDeviceName(deviceWechatInfo.getDeviceName());
                            wxqKickWhitelistVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
                        }
                    }

                    wxqKickWhitelistVoList.add(wxqKickWhitelistVo);
                }
            }
        }
        //返回到页面分页对象
        page.setRecords(wxqKickWhitelistVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 添加踢人白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqKickWhitelistDto
     * @return null
     */
    @Transactional
    public void add(WxqKickWhitelistDto wxqKickWhitelistDto){

        if(wxqKickWhitelistDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入白名单类型");
        }


        //临时封装成员wxid
        List<String> wxidList = wxqKickWhitelistDto.getWxidList();
        if(wxidList == null){
            wxidList = new ArrayList<>();
        }

        //选择的会员
        List<String> idList = wxqKickWhitelistDto.getIdList();
        if(idList == null){
            idList = new ArrayList<>();
        }

        String wxqKickWhitelistId = "";
        String groupWxid = null;
        String groupName = null;
        Long deviceUniqueId = null;
        String deviceId = null;
        if(wxqKickWhitelistDto.getType().intValue() == 0){ //群内白名单
            if(StringUtils.isBlank(wxqKickWhitelistDto.getGroupId())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群id");
            }

            //查询群存不存在
            String esName = EsIndexName.UZAI_WX_CONTACTS;
            String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxqKickWhitelistDto.getMerId());
            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, wxqKickWhitelistDto.getGroupId(), null);
            WxGroupInfoVo wxGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxGroupInfoVo.class);
            if(wxGroupInfoVo == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群不存在");
            }
            wxqKickWhitelistId = wxGroupInfoVo.getId();
            groupWxid = wxGroupInfoVo.getWxid();
            groupName = wxGroupInfoVo.getNick();
            deviceUniqueId = wxGroupInfoVo.getDeviceUniqueId();
            deviceId = wxGroupInfoVo.getDeviceId();

            //通过查询运营商其他索引分片获取分片索引
            String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxqKickWhitelistDto.getMerId());
            for (String memberId : idList) {
                Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, memberId, null);
                EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                if(esWxGroupMember != null){
                    wxidList.add(esWxGroupMember.getWxid());
                }
            }


        }else{ //所有群白名单
            wxqKickWhitelistId = wxqKickWhitelistDto.getMerId() + "_all_all";
        }

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入成员");
        }

        for (String wxid : wxidList) {
            String id = wxqKickWhitelistId + "_" + wxid;
            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_KICK_WHITElIST, id, null);
            if(map != null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, wxid+"已经在白名单中");
            }
        }

        for (String wxid : wxidList) {

            String id = wxqKickWhitelistId + "_" + wxid;

            WxqKickWhitelist wxqKickWhitelist = new WxqKickWhitelist();

            Integer now = DateUtil.getNowTime();
            wxqKickWhitelist.setId(id);
            wxqKickWhitelist.setMerId(wxqKickWhitelistDto.getMerId());
            wxqKickWhitelist.setGroupWxid(groupWxid);
            wxqKickWhitelist.setGroupName(groupName);
            wxqKickWhitelist.setDeviceUniqueId(deviceUniqueId);
            wxqKickWhitelist.setDeviceId(deviceId);
            wxqKickWhitelist.setWxid(wxid);
            wxqKickWhitelist.setRemark(wxqKickWhitelistDto.getRemark());
            wxqKickWhitelist.setType(wxqKickWhitelistDto.getType());
            wxqKickWhitelist.setCreateTime(now);
            wxqKickWhitelist.setUpdateTime(now);
            elasticsearchUtil.addData(wxqKickWhitelist, EsIndexName.UZAI_WXQ_KICK_WHITElIST, id);
        }

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 删除白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqKickWhitelistIdDto
     * @return null
     */
    @Transactional
    public void deleteById(WxqKickWhitelistIdDto wxqKickWhitelistIdDto){

        if(StringUtils.isBlank(wxqKickWhitelistIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_KICK_WHITElIST, wxqKickWhitelistIdDto.getId(), null);
        WxqKickWhitelist wxqKickWhitelist  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqKickWhitelist.class);
        if(wxqKickWhitelist == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有白名单不存在");
        }

        //删除私有白名单
        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_KICK_WHITElIST, wxqKickWhitelistIdDto.getId());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 查询踢人白名单详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqKickWhitelistIdDto
     * @return null
     */
    public WxqKickWhitelistVo findById(WxqKickWhitelistIdDto wxqKickWhitelistIdDto){
        if(StringUtils.isBlank(wxqKickWhitelistIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_KICK_WHITElIST, wxqKickWhitelistIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有白名单不存在");
        }

        WxqKickWhitelist wxqKickWhitelist  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqKickWhitelist.class);
        WxqKickWhitelistVo wxqKickWhitelistVo = new WxqKickWhitelistVo();
        BeanUtils.copyProperties(wxqKickWhitelist, wxqKickWhitelistVo);

        if(wxqKickWhitelistVo.getDeviceUniqueId() != null){
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxqKickWhitelistVo.getDeviceUniqueId(), wxqKickWhitelist.getMerId());
            if(deviceWechatInfo != null){
                wxqKickWhitelistVo.setDeviceName(deviceWechatInfo.getDeviceName());
                wxqKickWhitelistVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
            }
        }

        return wxqKickWhitelistVo;
    }
}
